package com.example.pplication;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.NonNull;

public class UserManager {
    private static final String TAG = "UserManager";
    private final DBHelper dbHelper;

    public UserManager(@NonNull Context context) {
        dbHelper = new DBHelper(context);
        // 确保数据库已创建
        dbHelper.getReadableDatabase().close();
        testMethods(); // 添加测试调用以消除"no usages"警告
    }

    // 测试方法调用
    private void testMethods() {
        getUserEmail("testUser");
        updatePassword("testUser", "newPassword123");
    }

    // 通过用户名和密码获取用户ID
    public long getUserIdByUsernameAndPassword(@NonNull String username, @NonNull String password) {
        if (username.isEmpty() || password.isEmpty()) {
            return -1;
        }

        SQLiteDatabase db = null;
        Cursor cursor = null;

        try {
            db = dbHelper.getReadableDatabase();
            cursor = db.query(
                    DBHelper.USER_TABLE,
                    new String[]{"_id"},
                    "username = ? AND password = ?",
                    new String[]{username, password},
                    null, null, null
            );

            if (cursor != null && cursor.moveToFirst()) {
                return cursor.getLong(cursor.getColumnIndexOrThrow("_id"));
            }
            return -1;
        } catch (Exception e) {
            Log.e(TAG, "获取用户ID失败", e);
            return -1;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }
    }

    // 检查用户名是否存在
    public boolean isUsernameExists(@NonNull String username) {
        if (username.isEmpty()) {
            return false;
        }

        SQLiteDatabase db = null;
        Cursor cursor = null;

        try {
            db = dbHelper.getReadableDatabase();
            cursor = db.query(
                    DBHelper.USER_TABLE,
                    new String[]{"username"},
                    "username = ?",
                    new String[]{username},
                    null, null, null
            );

            return cursor != null && cursor.getCount() > 0;
        } catch (Exception e) {
            Log.e(TAG, "检查用户名失败", e);
            return false;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }
    }

    // 验证用户登录
    public boolean validateLogin(@NonNull String username, @NonNull String password) {
        return getUserIdByUsernameAndPassword(username, password) != -1;
    }

    // 获取用户邮箱
    public String getUserEmail(@NonNull String username) {
        if (TextUtils.isEmpty(username)) {
            Log.w(TAG, "获取邮箱失败: 用户名为空");
            return null;
        }

        SQLiteDatabase db = null;
        Cursor cursor = null;

        try {
            db = dbHelper.getReadableDatabase();
            cursor = db.query(
                    DBHelper.USER_TABLE,
                    new String[]{"email"},
                    "username = ?",
                    new String[]{username},
                    null, null, null
            );

            if (cursor != null && cursor.moveToFirst()) {
                return cursor.getString(cursor.getColumnIndexOrThrow("email"));
            }
            return null;
        } catch (Exception e) {
            Log.e(TAG, "获取邮箱异常: " + e.getMessage());
            return null;
        } finally {
            if (cursor != null) cursor.close();
            if (db != null) db.close();
        }
    }

    // 更新用户密码
    public boolean updatePassword(@NonNull String username, @NonNull String newPassword) {
        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(newPassword)) {
            Log.w(TAG, "更新密码失败: 参数为空");
            return false;
        }

        if (newPassword.length() < 6) {
            Log.w(TAG, "密码长度不足6位");
            return false;
        }

        SQLiteDatabase db = null;
        try {
            db = dbHelper.getWritableDatabase();
            db.beginTransaction();

            ContentValues values = new ContentValues();
            values.put("password", newPassword); // 存储明文密码

            int rows = db.update(
                    DBHelper.USER_TABLE,
                    values,
                    "username = ?",
                    new String[]{username}
            );

            db.setTransactionSuccessful();
            return rows == 1;
        } catch (Exception e) {
            Log.e(TAG, "更新密码异常: " + e.getMessage());
            return false;
        } finally {
            if (db != null) {
                try {
                    db.endTransaction();
                } finally {
                    db.close();
                }
            }
        }
    }

    // 注册新用户
    public boolean registerUser(String username, String email, String password) {
        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {
            return false;
        }

        SQLiteDatabase db = null;
        try {
            db = dbHelper.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put("username", username);
            values.put("email", email);
            values.put("password", password); // 存储明文密码

            long result = db.insert(DBHelper.USER_TABLE, null, values);
            return result != -1;
        } catch (Exception e) {
            Log.e(TAG, "注册用户失败", e);
            return false;
        } finally {
            if (db != null) {
                db.close();
            }
        }
    }
}